package utils

import (
	"crypto/md5"
	"fmt"
	"strings"
	
	"gitee.com/liumou_site/go-network-monitoring/types"
)

// GenerateInterfaceID 根据网卡名称生成唯一ID
func GenerateInterfaceID(name string) string {
	// 使用网卡名称的哈希值作为ID，确保稳定性
	hash := md5.Sum([]byte(name))
	return fmt.Sprintf("iface_%x", hash)[:8]
}

// IsVirtualInterface 判断是否为虚拟网卡
func IsVirtualInterface(name string) bool {
	virtualPrefixes := []string{
		"docker", "veth", "virbr", "tun", "tap", "flannel", "cni",
		"br-", "vnet", "kube", "cilium", "calico", "weave", "lxc",
		"veth", "vxlan", "geneve", "gre", "gretap", "erspan",
		"ip6gre", "ip6gretap", "sit", "ipip", "ip6tnl", "nlmon",
	}

	for _, prefix := range virtualPrefixes {
		if strings.HasPrefix(strings.ToLower(name), prefix) {
			return true
		}
	}

	// 特殊虚拟接口
	virtualNames := map[string]bool{
		"lo": true, "dummy0": true, "bond0": true, "team0": true,
		"bridge": true, "ovs-system": true, "tunl0": true, "sit0": true,
	}

	// 包含特定关键词的虚拟接口
	lowerName := strings.ToLower(name)
	if strings.Contains(lowerName, "lxc") ||
		strings.Contains(lowerName, "veth") ||
		strings.Contains(lowerName, "loopback") ||
		strings.Contains(lowerName, "pseudo") {
		return true
	}

	return virtualNames[lowerName]
}

// IsLoopbackInterface 判断是否为回环接口
func IsLoopbackInterface(name string) bool {
	return name == "lo" || name == "Loopback"
}

// CalculateSpeedMbps 计算Mbps速率
func CalculateSpeedMbps(bytesPerSecond float64) float64 {
	return bytesPerSecond / 1024 / 1024 * 8
}

// CalculateGB 计算GB数值
func CalculateGB(bytes uint64) float64 {
	return float64(bytes) / 1024 / 1024 / 1024
}

// GenerateConnectionID 根据连接信息生成唯一ID
func GenerateConnectionID(conn types.ProcessConnection) string {
	// 使用连接信息生成唯一ID
	key := fmt.Sprintf("%s-%s-%d-%s-%d", conn.Protocol, conn.LocalAddr, conn.LocalPort, conn.RemoteAddr, conn.RemotePort)
	hash := md5.Sum([]byte(key))
	return fmt.Sprintf("conn_%x", hash)[:12]
}

// FormatPort 格式化端口号显示
func FormatPort(port int) string {
	if port == 0 {
		return "*"
	}
	return fmt.Sprintf("%d", port)
}

// GetConnectionDirection 获取连接方向
func GetConnectionDirection(remoteAddr string) string {
	if remoteAddr == "" || remoteAddr == "0.0.0.0" || remoteAddr == "::" {
		return "inbound"
	}
	return "outbound"
}

// UniqueInts 去重整数切片
func UniqueInts(input []int) []int {
	seen := make(map[int]bool)
	result := []int{}
	for _, val := range input {
		if !seen[val] {
			seen[val] = true
			result = append(result, val)
		}
	}
	return result
}

// UniqueStrings 去重字符串切片
func UniqueStrings(input []string) []string {
	seen := make(map[string]bool)
	result := []string{}
	for _, val := range input {
		if !seen[val] && val != "" {
			seen[val] = true
			result = append(result, val)
		}
	}
	return result
}
